package com.muyan.common.utils;

import com.muyan.common.bean.Params;
import com.muyan.common.constant.Const;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UrlUtil {

    /**
     * 默认构建 值经过Encode后的字符串链接 用于拼接链接
     */
    public static String bulidParams(Map<String, Object> params) {
        return bulidParams(params, true);
    }

    /**
     * 构建URL参数字符串拼接，
     *
     * @param params 参数
     * @param encode 是否UrlEncode
     * @return key=value&key1=value1
     */
    public static String bulidParams(Map<String, Object> params, boolean encode) {
        if (params == null || params.size() == 0) return "";
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (String key : params.keySet()) {
            Object value = params.get(key);
            if (value == null) value = "";
            try {
                if (first) {
                    first = false;
                    sb.append(key).append("=").append(encode ? URLEncoder.encode(value.toString(), Const.UTF_8) : value.toString());
                } else {
                    sb.append("&").append(key).append("=").append(encode ? URLEncoder.encode(value.toString(), Const.UTF_8) : value.toString());
                }
            } catch (Exception ignore) {
            }
        }
        return sb.toString();
    }

    /**
     * 从链接中获取请求参数，默认解码
     */
    public static Params getParams(String url) {
        return getParams(url, true);
    }

    /**
     * 从链接中获取请求参数
     */
    public static Params getParams(String url, boolean decode) {
        Params params = Params.build();
        if (StrUtil.isBlank(url)) return params;
        url = url.trim();
        url = url.substring(url.indexOf('?') + 1);
        String ps[] = url.split("&");
        String values[];
        for (String param : ps) {
            values = param.split("=");
            if (values.length > 1) {
                try {
                    params.put(values[0].trim(), decode ? URLDecoder.decode(values[1].trim(), Const.UTF_8) : values[1].trim());
                } catch (Exception ignore) {
                }
            } else {
                params.put(values[0], "");
            }
        }
        return params;
    }

    /**
     * 获取网址顶级域名
     * item.taobao.com -> .taobao.com
     */
    public static String getTopDomain(String url) {
        if (StrUtil.isBlank(url)) return null;
        try {
            Pattern pattern = Pattern.compile("(.*\\.)*(\\w*\\.\\w*)");
            Matcher matcher = pattern.matcher(url);
            if (matcher.find()) {
                return matcher.group(2);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
